import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Home from '@/views/home/index.vue'
import Article from '@/views/article/index.vue'
import Publish from '@/views/publish/index.vue'
import Layout from '@/views/layout/index.vue'
import { getItem } from '@/utils/auth.js'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'   
// 1: pagkage.json  2:index.js   3:index.vue

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  // {
  //   path: '/',
  //   redirect: '/home'
  // },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home', // 可以写相对地址也可以写绝对地址
        // 不是以/号开头这叫相对地址，相对于自己的父级  ： /layout/home
        // 绝对地址就是以/开头
        // alias: '/', // 别名：胡0号   小名：花姐
        component: Home
      },
      {
        path: '/article',
        component: Article
      },
      {
        path: '/publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置守卫
router.beforeEach((to, from, next) => {
 Nprogress.start()
  if(getItem()){
    if(to.path==='/login'){
      next('/home')
    }
    else{
      next()
    }
  }
  else{
    if(to.path==='/login'){
      next()
    }
    else{
      next('/login')
    }
  }

})


// 后置守卫
router.afterEach((to, from) => {
  Nprogress.done()
  // to and from are both route objects.
})
export default router
